<?php
namespace app\admin\controller;

use app\admin\business\AdminUser as AdminUserBus;
use app\admin\validate\AdminUser as AdminUserValidate;
use app\BaseController;
use think\facade\View;

/**
 * 后台登录页面
 */
class Login extends AdminBase {

    public function initialize() {
        if ($this->isLogin()) {
            return $this->redirect(url('/admin/index/index'), '302');
        }
    }

    /**
     * [index description]
     * @Author   cat
     * @DateTime 2020-05-10T16:07:17+0800
     * @return   [type]                   [description]
     */
    public function index() {
        return View::fetch();
    }

    public function check() {

        if (!$this->request->isPost()) {
            return show(config("status.error"), "请求方式错误");
        }

        // 参数检验 1、原生方式  2、TP6 验证机制
        $username = $this->request->param("username", "", "trim");
        $password = $this->request->param("password", "", "trim");
        $captcha  = $this->request->param("captcha", "", "trim");

        $data = [
            'username' => $username,
            'password' => $password,
            'captcha'  => $captcha,
        ];
        $validate = new AdminUserValidate();
        if (!$validate->check($data)) {
            return show(config("status.error"), $validate->getError());
        }

        //通过业务逻辑层处理业务
        try {
            $adminUserBus = new AdminUserBus();
            $result       = $adminUserBus->login($data);

        } catch (\Exception $e) {
            return show(config("status.error"), $e->getMessage());
        }

        if ($result) {
            return show(config("status.success"), "登录成功");
        } else {
            return show(config("status.error"), "登录失败");
        }

    }

}